# coding: utf-8
import os
from flask import Flask, render_template
import config
import logging
from flask_redis import FlaskRedis
from models import RoutingSession
from extensions import whooshee,bootstrap,moment,db,mail,login_manager,ckeditor,avatars,celery

redis_default = FlaskRedis(config_prefix='REDIS_URL')
redis_cache = FlaskRedis(config_prefix='REDIS_CACHE')
redis_game = FlaskRedis(config_prefix='REDIS_GAME')
def create_app(config_name=None):
    if config_name is None:
        config_name = os.getenv('FLASK_CONFIG', 'development')
    app = Flask(__name__)
    app.config.from_object(config.config[config_name])

    # 扩展实例化
    whooshee.init_app(app)
    bootstrap.init_app(app)
    moment.init_app(app)
    db.init_app(app)
    mail.init_app(app)
    login_manager.init_app(app)
    ckeditor.init_app(app)
    avatars.init_app(app)
    redis_default.init_app(app)
    redis_cache.init_app(app)
    redis_game.init_app(app)
    register_logging(app)
    configure_error_page(app)
    # celery.conf.update(app.config)
    register_api(app)

    from .admin import admin as admin_blueprint
    app.register_blueprint(admin_blueprint, url_prefix='/admin')
    from .blog import blog as blog_blueprint
    app.register_blueprint(blog_blueprint)
    from .auth import auth as auth_blueprint
    app.register_blueprint(auth_blueprint, url_prefix='/auth')

    return app

def register_api(app):
    import importlib
    interface_module = importlib.import_module("app_restful.restx")
    app.register_blueprint(interface_module.api_restful)

def configure_error_page(app):
    @app.errorhandler(404)
    def err404(e):
        return render_template('errors/404.html'), 404

    @app.errorhandler(502)
    def err404(e):
        return render_template('errors/404.html'), 502

def register_logging(app):
    import platform
    if 'macOS' in platform.platform():
        return
    from pathlib import Path
    log_dir = Path("/data/log")
    if not log_dir.exists():
        os.mkdir("/data", 0o755)
        os.mkdir("/data/log", 0o755)
    handler = logging.FileHandler('/data/log/blog_web.log',encoding='UTF-8')
    log_level = logging.DEBUG
    handler.setLevel(log_level)
    logging_format = logging.Formatter(
        '%(asctime)s - %(levelname)s - %(filename)s - %(process)d - %(thread)d - %(pathname)s - %(funcName)s - %(lineno)s: %(message)s')
    handler.setFormatter(logging_format)
    app.logger.addHandler(handler)


